package com.hm.PushCaseService.service.caseinfo;

import com.hm.PushCaseService.mapper.caseinfo.CaseInfoMapper;
import com.hm.PushCaseService.pojo.CaseBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class CaseService implements ICase {
    private static final Logger logger = LoggerFactory.getLogger(CaseService.class);

    @Qualifier("MainSqlSessionFactory")
    private final SqlSessionFactory sqlSessionFactory;

    public CaseService(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public List<CaseBean> queryCurrentDayCase() {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            CaseInfoMapper mapper = session.getMapper(CaseInfoMapper.class);
            Map<String, String> params = new HashMap<>();
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formattedDate = currentDate.format(formatter);
            params.put("startTime", formattedDate + " " + "00:00:00");
            params.put("endTime", formattedDate + " " + "23:59:5923");
            return mapper.queryCurrentDayCase(params);
        }
    }

    @Override
    public List<CaseBean> queryCaseByCode(String eventCode) {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            CaseInfoMapper mapper = session.getMapper(CaseInfoMapper.class);
            Map<String, String> params = new HashMap<>();
            params.put("eventCode", eventCode);
            return mapper.queryCaseByCode(params);
        }
    }

    @Override
    public void addBatchCase(List<CaseBean> fullCaseList) {
        if (fullCaseList != null && !fullCaseList.isEmpty()) {
            try (SqlSession session = sqlSessionFactory.openSession(true)) {
                CaseInfoMapper mapper = session.getMapper(CaseInfoMapper.class);
                mapper.addBatchCase(fullCaseList);
            }
        }
    }
}
